import { getUserInfoAPI } from "@/api/userApi";
import { UserInfo } from "@/views/about-me/models/userInfo";
import { message } from "ant-design-vue";
import { plainToClass } from "class-transformer";
import { defineStore } from "pinia";
import { useRouter } from "vue-router";

interface State {
  loading: boolean;
  userName:string;
  password:string;
  avatarUrl:string;
  role:string
}


// option store
export const useUserStore = defineStore('userStore',{
  state:()=>{
    return {
      loading:false,
      userName:'',
      password:'',
      avatarUrl:'',
      role:'',
    }as State
  },
  actions:{
    async handleInit(){
        const router = useRouter()
      try{
        this.loading = true
        // 根据id 获取用户信息
        const {data} = await getUserInfoAPI()
        const resultData = plainToClass(UserInfo,data.data)
        this.userName = resultData.userName
        this.avatarUrl = resultData.avatarUrl
        this.role = resultData.role
      }
      catch(e){
        // 跳转登录
        await message.info('请先登录')
        router.replace('/login')
        throw(e)
      }
      finally{
        this.loading = false
      }
    }
  }
})